package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl implements RoleService{

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);

        //条件查询分页数据
        List<Role> Roles=  roleMapper.findByCondition(queryString);

        //给PageInfo包装
        PageInfo<Role> pageInfo = new PageInfo<>(Roles);

        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());

        return pageResult;
    }

    @Override
    public void add(Integer [] permissionIds,Role role) {
        roleMapper.add(role);

        setRoleAndPermission(permissionIds,role.getId());
    }

    private void setRoleAndPermission(Integer[] permissionIds, Integer id) {
        if (permissionIds!=null && permissionIds.length>0){
            roleMapper.setRoleAndPermission(permissionIds,id);
        }

    }

    @Override
    public Role findById(Integer id) {
        return roleMapper.findById(id);
    }

    @Override
    public void edit(Integer[] permissionIds,Role role) {

        //删除中间表关系
        roleMapper.deleteAssociation(role.getId());
        //更新检查组
        roleMapper.edit(role);
        //重新设置检查组和检查项的中间表关系
        setRoleAndPermission(permissionIds,role.getId());
    }

    @Override
    public void deleteById(Integer id) {
        roleMapper.deleteById(id);
    }

    @Override
    public List<Permission> findAll() {
        List<Permission> list = roleMapper.findAll();
        return list;
    }

    @Override
    public List<Integer> findpermissionIdsByRoleId(Integer id) {
        return roleMapper.findpermissionIdsByRoleId(id);
    }
}
